# -*- coding: utf-8 -*-
"""
name: 课堂示例代码5 使用connectSlotsByName自动连接槽函数，注：自定义布局或ui布局都可。
version: 1.0
"""
import sys

from PyQt5 import QtCore, QtWidgets


class MyWidget(QtWidgets.QWidget):

    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent=parent)
        self.initUi()

    def initUi(self):
        # 设置ObjectName属性
        self.setObjectName("widget")
        self.resize(600, 350)
        self.setWindowTitle('案例 自动连接槽函数')
        
        self.label = QtWidgets.QLabel(self)
        self.label.setGeometry(QtCore.QRect(30, 30, 380, 30))
        self.label.setText("提示：请输入1到100的一个整数")

        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.setGeometry(QtCore.QRect(30, 80, 90, 30))

        self.label_2 = QtWidgets.QLabel(self)
        self.label_2.setGeometry(QtCore.QRect(130, 80, 20, 30))
        self.label_2.setText("+")

        self.lineEdit_2 = QtWidgets.QLineEdit(self)
        self.lineEdit_2.setGeometry(QtCore.QRect(160, 80, 90, 30))

        self.label_3 = QtWidgets.QLabel(self)
        self.label_3.setGeometry(QtCore.QRect(270, 80, 20, 30))
        self.label_3.setText("=")

        self.lineEdit_3 = QtWidgets.QLineEdit(self)
        self.lineEdit_3.setGeometry(QtCore.QRect(300, 80, 90, 30))
        self.lineEdit_3.setObjectName("lineEdit_3")

        self.pushButton = QtWidgets.QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(150, 140, 80, 50))
        # 设置ObjectName属性
        self.pushButton.setObjectName("pushButton")
        self.pushButton.setText('计算')

        # 使用ObjectName自动连接槽 on_ObjectName_signal()
        QtCore.QMetaObject.connectSlotsByName(self)

    def on_pushButton_pressed(self):
        try:
            self.lineEdit_3.clear()
            a = int(self.lineEdit.text())
            b = int(self.lineEdit_2.text())
            if 1 <= a <= 100 and 1 <= b <= 100:
                c = a + b
                QtWidgets.QMessageBox.information(self, "提示",
                                                  "计算成功，结果为%s" % str(c),
                                                  QtWidgets.QMessageBox.Ok)
                self.lineEdit_3.setText(str(c))
            else:
                QtWidgets.QMessageBox.warning(self,
                                              '警告：非法输入', '请输入1到100的一个整数',
                                              QtWidgets.QMessageBox.Close)

        except Exception as e:
            QtWidgets.QMessageBox.warning(self,
                                          '警告：非法输入',
                                          '请输入1到100的一个整数，错误信息：%s' % str(e),
                                          QtWidgets.QMessageBox.Close)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    form = MyWidget()
    form.show()
    sys.exit(app.exec_())
